package com.erp.auto.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.erp.auto.domain.ErpAutoPulishProductProject;
import com.erp.auto.domain.bo.ErpAutoPublishProductProjectBo;
import com.erp.auto.mapper.ErpAutoPulishProductProjectMapper;
import com.erp.auto.mapper.ErpAutoPulishProductProjectTaskMapper;
import com.erp.auto.service.IErpAutoPublishProductProjectService;
import com.ruoyi.ae.api.RemoteAeActivityService;
import com.ruoyi.ae.api.RemoteAeStoreInfoService;
import com.ruoyi.auto.api.domain.ErpAutoPulishProductProjectTask;
import com.ruoyi.auto.api.domain.ErpAutoSellerStoreConfig;
import com.erp.auto.mapper.ErpAutoSellerStoreConfigMapper;
import com.erp.auto.service.ErpAutoSellerStoreConfigService;
import com.erp.auto.service.ErpAutoViolationInfoService;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.utils.DateUtils;
import com.ruoyi.common.core.utils.HttpSendUtils;
import com.ruoyi.common.redis.utils.RedisUtils;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.gather.api.RemotePythonMethodCallService;
import com.ruoyi.shop.api.RemoteSellerStoreActivityService;
import com.ruoyi.shop.api.RemoteSellerStoreService;
import com.ruoyi.shop.api.domain.ErpSellerStoreEmpower;
import com.ruoyi.shop.api.domain.ErpSellerStorePromotionActivity;
import com.ruoyi.wallet.api.RemoteWalletExpandService;
import com.ruoyi.wallet.api.RemoteWalletService;
import com.ruoyi.wallet.api.domain.ErpDistributionUserWallet;
import com.ruoyi.wallet.api.domain.ErpSellerStoreWallet;
import lombok.AllArgsConstructor;
import org.apache.poi.ss.usermodel.DateUtil;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.Duration;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.*;

/**
 * 自动化店铺配置
 *
 * @author WXX
 * @date 2023-12-27 19:22:13
 */
@Service
@AllArgsConstructor
public class ErpAutoSellerStoreConfigServiceImpl implements ErpAutoSellerStoreConfigService {
    @Resource
    RestTemplate restTemplate;
    //    @Resource
//    private ERPConfig erpConfig;
    private final ErpAutoSellerStoreConfigMapper erpAutoSellerStoreConfigMapper;
    private final ErpAutoViolationInfoService violationInfoService;
    private final RemoteSellerStoreService remoteSellerStoreService;
    private final IErpAutoPublishProductProjectService erpAutoPulishProductProjectService;
    private final ErpAutoPulishProductProjectMapper erpAutoPulishProductProjectMapper;
    private final ErpAutoPulishProductProjectTaskMapper erpAutoPulishProductProjectTaskMapper;
    private final RemoteWalletService remoteWalletService;
    private final RemoteAeStoreInfoService remoteAeStoreInfoService;
    private final RemoteAeActivityService remoteAeActivityService;
    private final RemoteSellerStoreActivityService remoteSellerStoreActivityService;
    private final RemotePythonMethodCallService remotePythonMethodCallService;

    @Override
    public List<ErpAutoSellerStoreConfig> getList(ErpAutoSellerStoreConfig config) {
        LambdaQueryWrapper<ErpAutoSellerStoreConfig> queryWrapper = new LambdaQueryWrapper<>();
        if (config.getStoreAlias() != null) {
            queryWrapper.like(ErpAutoSellerStoreConfig::getStoreAlias, config.getStoreAlias());
        }
        if (config.getStoreId() != null) {
            queryWrapper.eq(ErpAutoSellerStoreConfig::getStoreId, config.getStoreId());
        }
        if (config.getUserId() == null) {
            return new ArrayList<ErpAutoSellerStoreConfig>();
        }
        if (config.getUserId() != 1L)
            queryWrapper.eq(ErpAutoSellerStoreConfig::getUserId, config.getUserId());
        if (config.getRevision() != null) {
            queryWrapper.eq(ErpAutoSellerStoreConfig::getRevision, config.getRevision());
        }
        List<ErpAutoSellerStoreConfig> storeConfigList = erpAutoSellerStoreConfigMapper.selectList(queryWrapper);
        for (ErpAutoSellerStoreConfig con : storeConfigList) {
            String cookie = remoteSellerStoreService.getCookieByStoreId(con.getStoreId());
            String channelId = remoteSellerStoreService.getChannelByStoreId(con.getStoreId());
            R<Object> sellerStoreInfoById = remoteSellerStoreService.getSellerStoreInfoById(con.getStoreId());
            String jsonString = JSONObject.toJSONString(sellerStoreInfoById.getData());
            ErpSellerStoreEmpower storeEmpower = JSONObject.parseObject(jsonString, ErpSellerStoreEmpower.class);
            if (storeEmpower != null) {
                con.setExpireTime(storeEmpower.getExpireTime() + "");
                con.setStoreUserName(storeEmpower.getStoreUserName());
                Long userId = storeEmpower.getUserId();
                // 查询用户的钱包余额
                ErpDistributionUserWallet wallet = remoteWalletService.getWalletByUserId(userId);
                if (wallet != null) {
                    con.setWalletMoney(wallet.getSettledAmount() + "");
                    // 查询测评余额
                    con.setEvaluationMoney(wallet.getEvaluateAmount() + "");
                }

            }
            con.setCookie(cookie);
            con.setChannelId(channelId);
            // 获取平台的违规分数
            int violationScore = violationInfoService.selectScoreByStoreId(con.getStoreId());
            con.setViolationScore(violationScore);
        }
        return storeConfigList;
    }

    @Override
    public ErpAutoSellerStoreConfig selectById(Long id) {
        return erpAutoSellerStoreConfigMapper.selectById(id);
    }

    @Override
    public String saveConfig(ErpAutoSellerStoreConfig config) {
        Long id = config.getId();
        int save;
        if (id == null) {
            ErpAutoSellerStoreConfig storeConfig = erpAutoSellerStoreConfigMapper
                    .selectOne(new LambdaQueryWrapper<ErpAutoSellerStoreConfig>()
                            .eq(ErpAutoSellerStoreConfig::getStoreId, config.getStoreId())
                            .eq(ErpAutoSellerStoreConfig::getStatus, 1));
            if (storeConfig != null) {
                return "店铺已绑定";
            }
            config.setBindTime(new Date());
            save = erpAutoSellerStoreConfigMapper.insert(config);
        } else {
            save = erpAutoSellerStoreConfigMapper.updateById(config);
        }
        return save + "";
    }

    @Override
    public int deleteConfigById(Long id) {
        ErpAutoSellerStoreConfig sellerStoreConfig = erpAutoSellerStoreConfigMapper.selectById(id);
        if (sellerStoreConfig == null) {
            return 0;
        }
        //TODO 应该将所有配置一并删除
        return erpAutoSellerStoreConfigMapper.deleteById(id);
    }

    @Override
    public boolean isDisable(Long storeId) {
        if (storeId == null) {
            return false;
        }
        ErpAutoSellerStoreConfig config = erpAutoSellerStoreConfigMapper.selectOne(new LambdaQueryWrapper<ErpAutoSellerStoreConfig>().eq(ErpAutoSellerStoreConfig::getStoreId, storeId));
        if (config != null) {
            return config.getStatus() == 1;
        }
        return false;
    }

    @Override
    public int updateStatusById(Long id) {
        ErpAutoSellerStoreConfig moduleConfig = erpAutoSellerStoreConfigMapper.selectById(id);
        if (moduleConfig.getStatus() == 0) {
            moduleConfig.setStatus(1);
        } else {
            moduleConfig.setStatus(0);
        }
        return erpAutoSellerStoreConfigMapper.updateById(moduleConfig);
    }

    @Override
    public R<Object> queryAutoStoreByStoreUserName(String storeUserName) {
        ErpAutoSellerStoreConfig moduleConfig = erpAutoSellerStoreConfigMapper.selectOne(
                new LambdaQueryWrapper<ErpAutoSellerStoreConfig>()
                        .eq(ErpAutoSellerStoreConfig::getStoreAlias, storeUserName)
                        .eq(ErpAutoSellerStoreConfig::getStatus, 1)
        );
        if (ObjectUtils.isNotNull(moduleConfig)) {
            return R.ok(moduleConfig.getUserId());
        } else {
            return R.fail("店铺未绑定自动化");
        }
    }

    @Override
    public R<Object> autoSubmitForReview(Long id) {
        List<ErpAutoSellerStoreConfig> storeConfigList = new ArrayList<>();
        if (ObjectUtils.isNotNull(id)) {
            //若店铺为null
            ErpAutoSellerStoreConfig store = erpAutoSellerStoreConfigMapper.selectById(id);
            if (Objects.isNull(store)) {
                return R.fail();
            } else {
                storeConfigList.add(store);
            }
        } else {
            storeConfigList = erpAutoSellerStoreConfigMapper.selectList(
                    new LambdaQueryWrapper<ErpAutoSellerStoreConfig>()
                            .eq(ErpAutoSellerStoreConfig::getStatus, 1)
                            .eq(ErpAutoSellerStoreConfig::getIsAutoSubmitOrder, 1)
            );
        }

        JSONObject map = new JSONObject();
        for (ErpAutoSellerStoreConfig store : storeConfigList) {
            map.put(store.getStoreAlias(), store.getStoreId());
        }

//        ResponseEntity<String> forEntity = restTemplate
//                .postForEntity(erpConfig.getEndpoint() + "/purchase/fpx/autoSubmitForReview", map, String.class);
//        String body = HttpSendUtils.getReturnPostBody( map.toJSONString(),"https://pbb2c.com/erp-api/purchase/fpx/autoSubmitForReview");
        String body = HttpSendUtils.getReturnPostBody(map.toJSONString(), "http://localhost:8860/purchase/fpx/autoSubmitForReview");

        JSONObject jsonObject = JSONObject.parseObject(body);
        if (jsonObject.getInteger("code") == 200) {
            return R.ok("自动提交完成");
        } else {
            return R.fail(jsonObject.getString("msg"));
        }
    }

    @Override
    public R<Object> getStoreListByUser() {
        Long userId = SecurityUtils.getUserId();
        LambdaQueryWrapper<ErpAutoSellerStoreConfig> queryWrapper = new LambdaQueryWrapper<>();
        if (userId != 1) {
            queryWrapper.eq(ErpAutoSellerStoreConfig::getUserId, userId);
        }
        List<ErpAutoSellerStoreConfig> list = erpAutoSellerStoreConfigMapper.selectList(queryWrapper);
        list.forEach(vo -> {
            Long storeId = vo.getStoreId();
            R<Object> sellerStoreInfoById = remoteSellerStoreService.getSellerStoreInfoById(storeId);
            String jsonString = JSONObject.toJSONString(sellerStoreInfoById);
            ErpSellerStoreEmpower storeEmpower = JSONObject.parseObject(jsonString, ErpSellerStoreEmpower.class);
            if (storeEmpower != null) {
                vo.setStoreUserName(storeEmpower.getStoreUserName());
            }
        });
        return R.ok(list);
    }

    @Override
    public R<Object> selectAutoStore(Long userId, Integer revision) {
        LambdaQueryWrapper<ErpAutoSellerStoreConfig> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(userId != null && userId != 1, ErpAutoSellerStoreConfig::getUserId, userId);
        queryWrapper.eq(revision != null, ErpAutoSellerStoreConfig::getRevision, revision);
        List<ErpAutoSellerStoreConfig> list = erpAutoSellerStoreConfigMapper.selectList(queryWrapper);
        List<Map<String, String>> storeList = new ArrayList<>();
        list.forEach(vo -> {
            Map<String, String> map = new HashMap<>();
            String storeAlias = vo.getStoreAlias();
            map.put("storeAlias", storeAlias);
            String storeName = vo.getStoreName();
            map.put("storeName", storeName);
            String storeId = vo.getStoreId().toString();
            map.put("storeId", storeId);
            storeList.add(map);
        });
        return R.ok(storeList);
    }

    /**
     * 检查自动化店铺授权情况
     *
     * @param id
     * @return
     */
    @Override
    public R<Object> checkAutoStoreAuth(String id) {
        List<ErpAutoSellerStoreConfig> erpAutoSellerStoreConfigs = new ArrayList<>();
        if (ObjectUtils.isNull(id)) {
            erpAutoSellerStoreConfigs = erpAutoSellerStoreConfigMapper.selectList(
                    new LambdaQueryWrapper<ErpAutoSellerStoreConfig>()
                            .eq(ErpAutoSellerStoreConfig::getStatus, 1)
            );
        } else {
            ErpAutoSellerStoreConfig erpAutoSellerStoreConfig = erpAutoSellerStoreConfigMapper.selectOne(
                    new LambdaQueryWrapper<ErpAutoSellerStoreConfig>()
                            .eq(ErpAutoSellerStoreConfig::getStatus, 1)
            );
            erpAutoSellerStoreConfigs.add(erpAutoSellerStoreConfig);
        }

        //同步token
        erpAutoPulishProductProjectService.synchronizationToken(null);

        for (ErpAutoSellerStoreConfig store : erpAutoSellerStoreConfigs) {
            //2、判断店铺Token是否有授权或是否生效
            R<Object> objectR = remoteAeStoreInfoService.querySellerStoreInfo(store.getStoreId().toString());
            if (objectR.getCode() != 200) {
                store.setAeTokenAuthStatus(0);
            } else {
                store.setAeTokenAuthStatus(1);
            }
            erpAutoSellerStoreConfigMapper.updateById(store);
        }
        return R.ok();
    }

    /**
     * 获取自动化店铺的storeUserName
     *
     * @return
     */
    @Override
    public R<Object> queryAutoStoreUserName() {
        List<String> storeUserNameLists = erpAutoSellerStoreConfigMapper.getNowStoreUserName();
        String join = String.join(",", storeUserNameLists.stream().map(String::valueOf).toArray(String[]::new));
        return R.ok(join);
    }

    /**
     * @return
     */
    @Override
    public R<Object> resetActivityAllStore() {
        //仍有用店铺，且店铺费自动化
        List<ErpAutoSellerStoreConfig> storeConfigs = erpAutoSellerStoreConfigMapper.selectList(
                new LambdaQueryWrapper<ErpAutoSellerStoreConfig>()
                        .le(ErpAutoSellerStoreConfig::getResetActivityRemark, DateUtils.getTime())
                        .le(ErpAutoSellerStoreConfig::getResetActivityHour, 200)
                        .eq(ErpAutoSellerStoreConfig::getStatus, 1)
        );

        for (ErpAutoSellerStoreConfig store : storeConfigs) {
            System.out.println("正在执行店铺" + store.getStoreAlias());
            R<Object> objectR = resetActivityByStoreUserName(store.getStoreAlias());
            System.out.println(objectR);
            if (objectR.getCode() == 200) {
                store.setResetActivityRemark(DateUtils.getTime());
                if (ObjectUtils.isNotNull(objectR.getData())) {
                    String data = objectR.getData().toString();
                    store.setResetActivityHour(Integer.parseInt(data));
                }
            } else {
                store.setResetActivityRemark(objectR.getMsg());
            }
            erpAutoSellerStoreConfigMapper.updateById(store);
        }

        return null;
    }


    /**
     * 重设活动，单店铺版
     *
     * @param storeUserName
     * @return
     */
    @Override
    public R<Object> resetActivityByStoreUserName(String storeUserName) {
        /**
         * 1、获取当前店铺的所有上架计划的活动 去重
         * 2、获取该店铺的所有正在执行活动活动（Ongoing）
         * 3、循环判断 判断该计划的活动是否在列表中
         *  3-1 如果不在，则证明已经过期，标记待创建新活动
         *  3-2 如果在，则判断过期时间距离
         *     3-2-1 如果距离过期时间大于一天，则不进行处理
         *     3-2-2 如果距离过期时间小于一天，标记创建新活动
         * 4、执行标记活动
         *  4-1 创建活动名字，活动名字以年份+月份+随机四位数组成
         *  4-2 调用孙哥接口，创建活动，同步活动
         *  4-3 替换上架计划中活动id
         *  4-4 调用孙哥接口，导出+导入活动商品
         */
        R<Object> storeEmpowerObject = remoteSellerStoreService.getSellerStoreEmpowerByCnCode(storeUserName);
        if (storeEmpowerObject.getCode() != 200) {
            return R.fail("获取店铺授权信息失败");
        }
        String storeEmpowerString = JSONObject.toJSONString(storeEmpowerObject.getData());
        ErpSellerStoreEmpower storeEmpower = JSONObject.parseObject(storeEmpowerString, ErpSellerStoreEmpower.class);

        remoteAeActivityService.selectStoreOngoingPromotions("100", storeEmpower.getId().toString());


        List<ErpAutoPulishProductProject> projectList = erpAutoPulishProductProjectMapper.selectList(
                new LambdaQueryWrapper<ErpAutoPulishProductProject>()
                        .eq(ErpAutoPulishProductProject::getStoreUserName, storeUserName)
                        .isNotNull(ErpAutoPulishProductProject::getProductDiscountId)
                        .groupBy(ErpAutoPulishProductProject::getProductDiscountId)
        );

//        //获取该店铺的所有正在执行活动（Ongoing）
//        R<Object> objectR = remoteAeActivityService.queryStoreOngoingPromotionsMsg(storeUserName);
//        String str = (String) objectR.getData();
//        //循环速卖通获取的活动
//        List<ErpSellerStorePromotionActivity> activityList = JSONArray.parseArray(str, ErpSellerStorePromotionActivity.class);
//        if (Objects.isNull(activityList)) {
//            return R.fail("活动为空");
//        }
        Map<String, Object> activityMap = new HashMap<>();
        for (ErpAutoPulishProductProject project : projectList) {
            //放入map中
            activityMap.put(project.getProductDiscountId().toString(), project);
        }
        Long absoluteHoursBetween = null;
        for (String key : activityMap.keySet()) {
            ErpSellerStorePromotionActivity activitySel = new ErpSellerStorePromotionActivity();
            activitySel.setPromotionId(key);
            activitySel.setStoreId(storeEmpower.getId());
            R<Object> objectR = remoteSellerStoreService.getPromotionActivityInfo(activitySel);
            if (objectR.getCode() != 200) {
                return R.fail("活动获取失败");
            }
            String activityStr = JSONObject.toJSONString(objectR.getData());
            ErpSellerStorePromotionActivity activity = JSONObject.parseObject(activityStr, ErpSellerStorePromotionActivity.class);
//            if (Objects.isNull(activity)) {
//                //说明活动现在已经不为正在执行状态
//                //标记待创建新活动
//                signCreateActivityBegin(storeEmpower, key, DateUtils.getTime());
//            } else {
            //判断距离过期时间距离
            //获取当前的过期时间
            if (Objects.isNull(activity)) {
                continue;
            }
            String endTime = activity.getEndTime();
            System.out.println(endTime);
            //判断过期时间和当前时间长度，是否大于24小时
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            LocalDateTime givenDateTime = LocalDateTime.parse(endTime, formatter);

            // 获取当前日期时间
            LocalDateTime now = LocalDateTime.now();

            // 计算时间差
            Duration duration = Duration.between(now, givenDateTime);

            // 将时间差转换为小时
            long hoursBetween = duration.toHours();

            // 注意：如果当前时间晚于给定的时间，toHours()将返回一个负数
            // 如果你想得到一个绝对值（即不考虑正负），可以使用Math.abs()
            absoluteHoursBetween = hoursBetween;

            // 输出结果
            System.out.println("当前时间: " + now);
            System.out.println("结束时间: " + givenDateTime);
            System.out.println("相差的小时数: " + absoluteHoursBetween);
            if (absoluteHoursBetween.intValue() >= 96) {
                //大于24小时不进行处理
                System.out.println("暂不处理");
                continue;
            } else {
                //小于24小时，标记待创建新活动
                R<Object> objectR1 = signCreateActivityBegin(storeEmpower, key, activity.getEndTime());
                if (objectR1.getCode() != 200) {
                    return R.fail(objectR1.getMsg());
                }
            }
//            }


        }

        return R.ok(absoluteHoursBetween);

    }

    @Override
    public R<Object> supplementResetActivityError(String storeUserName, String activityId) {
        //2、获取到目前的活动
        List<ErpAutoPulishProductProject> projectList = erpAutoPulishProductProjectMapper.selectList(
                new LambdaQueryWrapper<ErpAutoPulishProductProject>()
                        .eq(ErpAutoPulishProductProject::getStoreUserName, storeUserName)
                        .eq(ErpAutoPulishProductProject::getProductDiscountId, activityId)
        );

        for (ErpAutoPulishProductProject project : projectList) {
            //1、获取到店铺任务表中所有的为0的任务
            List<ErpAutoPulishProductProjectTask> taskList = erpAutoPulishProductProjectTaskMapper.selectList(
                    new LambdaQueryWrapper<ErpAutoPulishProductProjectTask>()
                            .isNotNull(ErpAutoPulishProductProjectTask::getAeProductId)
                            .eq(ErpAutoPulishProductProjectTask::getProjectId, project.getId())
                            .eq(ErpAutoPulishProductProjectTask::getResetActivityStatus, 0)
            );
            addProductToActivityByPython(taskList, project);
        }
        return R.ok();

    }

    @Override
    public R<Object> supplementResetActivityErrorZero() {

        //1 获取到有哪些店铺需要补充0
        List<String> storeUserNameList = erpAutoSellerStoreConfigMapper.queryResetActivityStatusZeroTask();

        for (String storeUserName : storeUserNameList) {
            //2 循环中，获取到该店铺的最新活动
            List<ErpAutoPulishProductProject> projectList = erpAutoPulishProductProjectMapper.selectList(
                    new LambdaQueryWrapper<ErpAutoPulishProductProject>()
                            .eq(ErpAutoPulishProductProject::getStoreUserName, storeUserName)
            );

            for (ErpAutoPulishProductProject project : projectList) {
                //1、获取到店铺任务表中所有的为0的任务
                List<ErpAutoPulishProductProjectTask> taskList = erpAutoPulishProductProjectTaskMapper.selectList(
                        new LambdaQueryWrapper<ErpAutoPulishProductProjectTask>()
                                .isNotNull(ErpAutoPulishProductProjectTask::getAeProductId)
                                .eq(ErpAutoPulishProductProjectTask::getProjectId, project.getId())
                                .eq(ErpAutoPulishProductProjectTask::getStatus, 2)
                                .eq(ErpAutoPulishProductProjectTask::getResetActivityStatus, 0)
                );
                addProductToActivityByPython(taskList, project);
            }
        }

        return R.ok();
    }

    //标记执行活动
    public R<Object> signCreateActivityBegin(ErpSellerStoreEmpower storeEmpower, String oldActivityId, String time) {

        /**
         *    4-1 创建活动名字，活动名字以年份+月份+随机四位数组成
         *    4-2 调用孙哥接口，创建活动，同步活动
         *    4-3 替换上架计划中活动id
         *    4-4 调用孙哥接口，导出+导入活动商品
         */
        //根据店铺id，将所有为1和3的都设为0
        erpAutoPulishProductProjectTaskMapper.resetActivityStatusByStoreUserName(storeEmpower.getStoreUserName());

        DateTimeFormatter formatterTwo = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        DateTimeFormatter formatterTest = DateTimeFormatter.ISO_LOCAL_DATE_TIME;

        //根据当前年份+月份+随机四位数创建字符串
        // 获取当前日期
        LocalDateTime now = LocalDateTime.parse(time, formatterTwo);

        // 创建一个Random对象
        Random random = new Random();
        // 生成一个随机的四位数
        int randomFourDigits = random.nextInt(9000) + 1000; // 确保是四位数
        // 使用DateTimeFormatter来格式化日期（虽然在这个例子中我们只需要年份和月份）
        // 但如果你想包含日期，你可以使用更复杂的格式化模式
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMM");
        // 创建最终的字符串
        String finalString = now.format(formatter) + "-" + String.format("%04d", randomFourDigits);
        System.out.println(finalString);
        //创建并同步活动

        //设置活动名
        String productDiscountName = finalString;
        //同步活动
        // 格式化当前时间
//        String nowFormatted = now.format(formatterTwo);

        String nowFormatted = now.toString();
        //特殊情况
//        String nowFormatted = String.valueOf(LocalDateTime.parse(DateUtils.getTime(),formatterTwo));
        LocalDateTime parse = LocalDateTime.parse(nowFormatted, formatterTest);
//        LocalDateTime zeroHourOld = parse.plusDays(1).withHour(0).withMinute(0).withSecond(0).withNano(57601);
//        LocalDateTime zeroHour = zeroHourOld.plusHours(18);
//        LocalDateTime zeroHour = parse.withHour(0).withMinute(0).withSecond(0).withNano(0);
        LocalDateTime zeroHour = parse.plusHours(8).plusSeconds(1);
//        昨天的零点
        System.out.println(zeroHour);

        //创建活动
        ErpSellerStorePromotionActivity activity = new ErpSellerStorePromotionActivity();
        activity.setUserId(storeEmpower.getUserId());
        Long storeId = storeEmpower.getId();
        activity.setStoreId(storeId);
        activity.setPromotionName(productDiscountName);

        activity.setStartTime(zeroHour.format(formatterTwo).toString());
        // 原始日期时间
//                String startTime = zeroHour.format(formatter);
        LocalDateTime originalDateTime = LocalDateTime.parse(nowFormatted, formatterTest);
//                LocalDateTime originalDateTime = LocalDateTime.parse(nowDate);
        // 计算三个月后的日期时间
        LocalDateTime oneMonthLater = originalDateTime.plus(3, ChronoUnit.MONTHS);
        activity.setEndTime(oneMonthLater.format(formatterTwo));

        activity.setErpStatus("0");
        activity.setHasPromo("false");
//                erpSellerStorePromotionActivityMapper.insert(activity);
//                调用接口，上传至平台 //TODO 爬虫相关，暂不执行

        R<Object> activityToAe = remotePythonMethodCallService.createActivityByPython(storeId.toString(), activity.getStartTime(), activity.getEndTime(), productDiscountName);
        if (activityToAe.getCode() == 200) {
            //创建成功，拿到对应值
            //同步活动
            remoteAeActivityService.selectStoreOngoingPromotions("1", storeId.toString());
        }
//        else {
//            activity.setStartTime(zeroHourOld.format(formatter).toString());
//            activityToAe = remotePythonMethodCallService.createActivityByPython(storeId.toString(), activity.getStartTime(), activity.getEndTime(), productDiscountName);
//            if (activityToAe.getCode() == 200) {
//                remoteAeActivityService.selectStoreOngoingPromotions("1", storeId.toString());
//            } else {
//                return R.fail("活动创建失败");
//            }
//        }

        ErpSellerStorePromotionActivity activitySel = new ErpSellerStorePromotionActivity();
        activitySel.setStoreId(storeId);
        activitySel.setPromotionName(productDiscountName);
        //保存活动id
        R<Object> activityInfoR = remoteSellerStoreActivityService.selectActivityInfo(activitySel);
        if (activityInfoR.getCode() != 200) {
            return R.fail("活动查询异常");
        }
        String activityString = JSONObject.toJSONString(activityInfoR.getData());
        activitySel = JSONObject.parseObject(activityString, ErpSellerStorePromotionActivity.class);
        String newActivityId = activitySel.getPromotionId();
        //找到project中活动是该id的活动，进行替换
        ErpAutoPulishProductProject projectUpdate = new ErpAutoPulishProductProject();
        projectUpdate.setProductDiscountId(Long.valueOf(newActivityId));
        erpAutoPulishProductProjectMapper.update(
                projectUpdate,
                new LambdaQueryWrapper<ErpAutoPulishProductProject>()
                        .eq(ErpAutoPulishProductProject::getProductDiscountId, oldActivityId));

        addProductToActivityByPython(newActivityId);
        //确认结果
        return R.ok();
    }

    public R<Object> addProductToActivityByPython(String newActivityId) {
        List<ErpAutoPulishProductProject> projectList = erpAutoPulishProductProjectMapper.selectList(
                new LambdaQueryWrapper<ErpAutoPulishProductProject>().eq(ErpAutoPulishProductProject::getProductDiscountId, newActivityId)
        );
        for (ErpAutoPulishProductProject project : projectList) {
            //将该计划中所有为1和3的设为0
            ErpAutoPulishProductProjectTask taskUpdate = new ErpAutoPulishProductProjectTask();
            taskUpdate.setResetActivityStatus(0);
            erpAutoPulishProductProjectTaskMapper.update(
                    taskUpdate
                    , new LambdaQueryWrapper<ErpAutoPulishProductProjectTask>()
                            .eq(ErpAutoPulishProductProjectTask::getProjectId, project.getId())
                            .in(ErpAutoPulishProductProjectTask::getResetActivityStatus, 1, 3)
            );

            //调用接口
            List<ErpAutoPulishProductProjectTask> taskList = erpAutoPulishProductProjectTaskMapper.selectList(
                    new LambdaQueryWrapper<ErpAutoPulishProductProjectTask>()
                            .eq(ErpAutoPulishProductProjectTask::getProjectId, project.getId())
                            .isNotNull(ErpAutoPulishProductProjectTask::getAeProductId)
                            .in(ErpAutoPulishProductProjectTask::getStatus, 2)
                            .eq(ErpAutoPulishProductProjectTask::getResetActivityStatus, 0)
            );
            if (taskList.size() > 0) {
                addProductToActivityByPython(taskList, project);
            }
        }
        return R.ok();
    }


    //    @Async
    public R<Object> addProductToActivityByPython(List<ErpAutoPulishProductProjectTask> taskList, ErpAutoPulishProductProject project) {
        System.out.println("任务总数：" + taskList.size());
        int i = 0;
        int j = 0;
        for (ErpAutoPulishProductProjectTask task : taskList) {
            R<Object> objectR = remotePythonMethodCallService.addProductToActivity(
                    task.getStoreId().toString(),
                    project.getProductDiscount(),
                    project.getProductDiscountId().toString(),
                    task.getAeProductId().toString()
            );

            if (objectR.getCode() == 200) {
                //转移成功
                task.setResetActivityRemark("最后设置折扣活动" + DateUtils.getTime());
                task.setResetActivityStatus(1);
                i++;
            } else {
                task.setResetActivityRemark(objectR.getMsg());
                task.setResetActivityStatus(2);
                j++;
            }
            erpAutoPulishProductProjectTaskMapper.updateById(task);

        }
        System.out.println("执行结束,成功" + i + "个，失败" + j + "个");
        return R.ok();
    }


    /**
     * 设置店铺是否开启自动化提交订单
     *
     * @param id
     * @param type
     * @return
     */
    @Override
    public R<Object> setAutoSubmitStore(Long id, Integer type) {
        ErpAutoSellerStoreConfig store = erpAutoSellerStoreConfigMapper.selectById(id);
        if (ObjectUtils.isNull(store)) {
            //店铺不存在
            return R.fail("店铺不存在");
        }
        store.setIsAutoSubmitOrder(type);
        erpAutoSellerStoreConfigMapper.updateById(store);
        return R.ok("设置成功");
    }
}
